package com.itzhihao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itzhihao.common.constant.ExistStatus;
import com.itzhihao.entity.Address;
import com.itzhihao.mapper.AddressMapper;
import com.itzhihao.service.IAddressService;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address>
    implements IAddressService {

    @Resource
    private AddressMapper addressMapper;

    @Override
    public Address getDetail(Long id) {
        LambdaQueryWrapper<Address> queryWrapper  = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getIsDeleted,ExistStatus.EXIST_STATUS.ordinal())
                    .eq(Address::getId,id);
        return addressMapper.selectOne(queryWrapper);
    }

    @Override
    public Boolean setDefault(Address address) {
        Address defaultAddr = getDefault();
        if(address.getId().equals(defaultAddr.getId())){
            return false;
        }
        Boolean aBoolean = setNotDefault(defaultAddr);
        if(aBoolean){
            LambdaUpdateWrapper<Address> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Address::getIsDefault,1);
            int update = addressMapper.update(address, updateWrapper);
            return update>0?true:false;
        }
        return false;
    }

    public Boolean setNotDefault(Address address){
        LambdaUpdateWrapper<Address> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Address::getIsDefault,0);
        int update = addressMapper.update(address, updateWrapper);
        return update>0?true:false;
    }

    @Override
    public Address getDefault() {
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getIsDefault,1);
        queryWrapper.eq(Address::getStakeholderId,userId);
        queryWrapper.eq(Address::getIsDeleted,ExistStatus.EXIST_STATUS.ordinal());
        Address address = addressMapper.selectOne(queryWrapper);
        return address;
    }


    @Override
    public boolean updateOrSave(Address address) {
        Long userId = SecurityUtils.getUserId();
        String name = SecurityUtils.getUsername();
        address.setStakeholderId(userId);
        address.setUpdateTime(DateUtils.getNowDate());
        address.setUpdateBy(name);
        // 取消掉原来的默认地址
        if(address.getIsDefault() != null && address.getIsDefault() == 1){
            Address aDefault = getDefault();
            if(aDefault != null){
                setNotDefault(aDefault);
            }
        }
        int i = 0;
        // 修改
        if(address.getId() != null){
            i = addressMapper.updateById(address);
        }else{
            address.setCreateBy(name);
            address.setIsDeleted(ExistStatus.EXIST_STATUS.ordinal());
            address.setUpdateTime(DateUtils.getNowDate());
            Integer addrNum = getAddrNum();
            if(addrNum == 0){
                address.setIsDefault(1);
            }
            i = addressMapper.insert(address);
        }
        if(i > 0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取某一用户地址总数
     * @return
     */
    public Integer getAddrNum(){
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getStakeholderId,userId);
        queryWrapper.eq(Address::getIsDeleted,ExistStatus.EXIST_STATUS.ordinal());
        return addressMapper.selectCount(queryWrapper).intValue();
    }

    @Override
    public TableDataInfo getList(PageDomain pageDomain) {
        Long userId = SecurityUtils.getUserId();
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();

        queryWrapper
                .lambda()
                .eq(Address::getStakeholderId,userId)
                .eq(Address::getIsDeleted,ExistStatus.EXIST_STATUS.ordinal());
        Page<Address> page = new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
        addressMapper.selectPage(page,queryWrapper);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询到"+page.getCurrent()+"条数据");
        tableDataInfo.setRows(page.getRecords());
        System.out.println(page.getTotal());
        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }

    @Override
    public boolean deleteById(Long id) {
        LambdaUpdateWrapper<Address> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Address::getIsDeleted, ExistStatus.NO_EXIST_STATUS.ordinal());
        updateWrapper.eq(Address::getId,id);
        int i = addressMapper.update(null, updateWrapper);
        if(i > 0){
            return true;
        }else{
            return false;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteByIds(List<Long> idLongList) {
        for (Long id:idLongList
             ) {
            boolean b = deleteById(id);
            if(!b){
                return false;
            }
        }
        return true;
    }
}
